import React, { useReducer } from "react"
import { Button } from 'antd'

const UseReducerPage: React.FC = () => {
    return (<>
        <div>
            <h1>Father</h1>
            <Father></Father>
        </div>
    </>)
}
const defaultState = { name: 'liulongbin', age: 16.56 }
// 定义状态的数据类型
type UserType = typeof defaultState
// 1. 定义 action 的类型
type ActionType = { type: 'UPDATE_NAME'; payload: string } | { type: 'INCREMENT'; payload: number } | { type: 'RESET' }
const Father: React.FC = () => {
    // 给 initState 指定类型为 UserType
    const reducer = (prevState: UserType, action: ActionType) => {
        // 打印 action 的值，终端显示的值为：
        console.log('触发了 reducer 函数', action)
        // 3. 删掉之前的代码，再重复编写这段逻辑的时候，会出现 TS 的类型提示，非常 Nice
        switch (action.type) {
            case 'RESET':
                return initAction(defaultState)
            case 'INCREMENT':
                return { ...prevState, age: prevState.age + action.payload }
            case 'UPDATE_NAME':
                return { ...prevState, name: action.payload }
            default:
                return prevState
        }
    }
    const initAction = (initState: UserType) => {
        console.log('触发了 initAction 函数,只会在函数初始化的时候调用');

        // 把 return 的对象，作为 useReducer 的初始值
        return { ...initState, age: Math.round(Math.abs(initState.age)) || 18 }
    }
    const [state, dispatch] = useReducer(reducer, defaultState, initAction)
    const onChangeName = () => {
        dispatch({ type: 'UPDATE_NAME', payload: '刘龙彬' })
    }
    return (<>
        <Button type="primary" onClick={onChangeName}>修改 name 的值</Button>
        <div className="father">
            <Son1 {...state} dispatch={dispatch} />
            <Son2 {...state} dispatch={dispatch} />
        </div>
    </>)
}
const Son1: React.FC<UserType & { dispatch: React.Dispatch<ActionType> }> = (props) => {
    const { dispatch, ...userType } = props
    const add = () => {
        dispatch({
            type: "INCREMENT",
            payload: 1
        })
    }
    return <>
        <p>Son1用户信息：</p>
        <p>{JSON.stringify(userType)}</p>
        <Button onClick={add} type="primary">+1</Button>
    </>
}
const Son2: React.FC<UserType & { dispatch: React.Dispatch<ActionType> }> = (props) => {
    const { dispatch, ...userType } = props
    const reduce = () => {
        dispatch({
            type: "INCREMENT",
            payload: -2
        })
    }
    return <><p>Son2用户信息：</p>
        <p>{JSON.stringify(userType)}</p>
        <Button onClick={reduce} type="primary">-2</Button>
        <GrandSon dispatch={dispatch}></GrandSon>
    </>
}
const GrandSon: React.FC<{ dispatch: React.Dispatch<ActionType> }> = (props) => {
    const reset = () => {
        props.dispatch({ type: 'RESET' })
    }
    return <>
        <h2>GrandSon</h2>
        <Button onClick={reset}>重置数据</Button>
    </>
}
export default UseReducerPage